package game.client;

import game.client.net.GameConnection;
import game.client.net.PlayerPositionSender;
import game.common.world.Vector;

import java.util.Random;

public class UpdateLoop implements Runnable {

	private Vector playerPosition;
	
	private PlayerPositionSender positionSender;
	
	public UpdateLoop(Vector playerPosition, GameConnection connection) {
		this.playerPosition = playerPosition;
		this.positionSender = new PlayerPositionSender(connection);
	}
	
	@Override
	public void run() {		
		boolean revert = false;
		Random rnd = new Random();
		while (true){
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			int steps = rnd.nextInt(5);
			if (rnd.nextBoolean()){
				int newX = (int)this.playerPosition.getXf() + (revert ? -1 * steps : steps);
				if (newX < 0 || newX > 800){
					newX = revert ? 0 : 800;
					revert = !revert;
				}
				this.playerPosition.setX(newX);
			}
			else{
				int newY = (int)this.playerPosition.getYf() + (revert ? -1 * steps : steps);
				if (newY < 0 || newY > 600){
					newY = revert ? 0 : 600;
					revert = !revert;
				}
				this.playerPosition.setY(newY);
			}
			
			try {
				positionSender.send(playerPosition);
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(1);
			}
		}
	}
	
}
